# coding:utf-8
import re
import sys
import socket

from multiprocessing import Process
from Setting import *

class HTTPServer(object):
    """
    服务器类
    """
    def __init__(self, application):
        """
        构造函数
        :param application:指的是框架的app
        """
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.app = application
            
    def start(self):
        self.server_socket.listen(QUEUE_NUMBER)      
        while True:
            client_socket, client_addres = self.server_socket.accept()
            handle_client_process = Process(target=self.handle_client, args=(client_socket,))
            handle_client_process.start()
            client_socket.close()
    
    def start_response(self, status, headers):
        """
        构造响应头
        """
        response_headers = "HTTP/1.1 " + status + "\r\n"
        for header in headers:
            response_headers += "%s: %s\r\n" % header
        self.response_headers = response_headers

    def handle_client(self, client_socket):
        """
        处理客户端请求
        :param client_socket: 客户端的socket
        """
        request_data = client_socket.recv(1024)
        print("request data:", request_data)
        if request_data == b'':
            client_socket.close()
        else:
            request_lines = request_data.splitlines()
            try:
                request_start_line = request_lines[0]
            except IndexError:
                request_start_line = u''
            file_name = re.match(r"\w+ +(/[^ ]*) ", request_start_line.decode("utf-8")).group(1)
            method = re.match(r"(\w+) +/[^ ]* ", request_start_line.decode("utf-8")).group(1)
              
            env = {
                "PATH_INFO": file_name,
                "METHOD": method
            }
            response_body = self.app(env, self.start_response)
            response = self.response_headers + "\r\n" + response_body
             
            # 向客户端返回响应数据
            client_socket.send(bytes(response, 'utf-8'))
        
            # 关闭客户端链接
            client_socket.close()

    def bind(self, ip_port):
        self.server_socket.bind(ip_port) # 绑定任意IP


def main():
    if len(sys.argv) < 2:
        sys.exit("python3 MyWebServer.py Module:app")
    module_name, app_name = sys.argv[1].split(":")
    m = __import__(module_name)
    app = getattr(m, app_name)
    http_server = HTTPServer(app)
    http_server.bind(IP_PORT)  
    http_server.start()

if __name__ == "__main__":
    main()   
